package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
@Service
public class StrategyServiceImpl implements IStrategyService {
    @Autowired
    private StrategyRepository strategyRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private IStrategyCatalogService strategyCatalogService;
    @Autowired
    private IStrategyThemeService strategyThemeService;
    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        strategyRepository.save(strategy);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public Strategy get(String id) {
        return strategyRepository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> lists() {
        return strategyRepository.findAll();
    }
    //分页查询
    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        //创建查询对象
        Query query = new Query();
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if(StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        //拿到查询对象总条数
        long count = mongoTemplate.count(query, Strategy.class);
        if (count == 0){
            return Page.empty();//直接返回一个空集合
        }
        //执行分页
        PageRequest pageRequest =PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
       query.with(pageRequest);
        //查询数据
        List<Strategy> list = mongoTemplate.find(query, Strategy.class);
        return new PageImpl<>(list,pageRequest,count);
    }

    /**
     * 添加和修改功能
     * @param strategy
     */
    @Override
    public void saveOUpdate(Strategy strategy) {
        //冗余字段维护
        //1:目的地名称,通过分类id查询目的地和目的地名称//目的地id
        StrategyCatalog strategyCatalog=strategyCatalogService.get(strategy.getCatalogId());
        strategy.setDestId(strategyCatalog.getDestId());
        strategy.setDestName(strategyCatalog.getDestName());
        //分类名称
        strategy.setCatalogName(strategyCatalog.getName());
        //主题名称,通过主题id查询
        StrategyTheme strategyTheme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(strategyTheme.getName());
        //是否国外,利用复目的地id,吐丝
        List<Destination> serviceTost = destinationService.createTost(strategyCatalog.getDestId());
        //判断
        if (serviceTost !=null && serviceTost.size()>0){
            //拿他最大那个,就是第一个值
            Destination destination = serviceTost.get(0);
            if ("中国".equals(destination.getName())){
                strategy.setIsabroad(Strategy.ABROAD_NO);//中国
            }else {
                strategy.setIsabroad(Strategy.ABROAD_YES);//外国
            }
        }
        if (StringUtils.hasLength(strategy.getId())){
            Strategy str = this.get(strategy.getId());
            strategy.setFavornum(str.getFavornum());
            strategy.setReplynum(str.getReplynum());
            strategy.setSharenum(str.getSharenum());
            strategy.setCreateTime(str.getCreateTime());
            strategy.setViewnum(str.getViewnum());
            //1先查询  2再替换  3修改
            //这个是特殊的类,
            this.update(strategy);
        }else {
            //创建时间,只有添加有
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }

    }

    @Override
    public void changeState(String id, int state) {
        //创建查询对象
        Query query = new Query();
        //条件
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        //等同于条件中的set
        update.set("state",state);
        //利用MongoDB方法
        mongoTemplate.updateMulti(query,update,Strategy.class);
    }

    /**
     * 通过目的地id查询攻略明细,截取前3
     * @param destId
     * @return
     */
    @Override
    public List<Strategy> viewnumTop3(String destId) {
        //添加截取功能
        Pageable pageable =PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");

        return strategyRepository.findByDestId(destId,pageable);
    }

    @Override
    public List<Strategy> queryfindByDestName(String keyword) {
        return strategyRepository.findByDestName(keyword);
    }
}
